package person.twj.jwt.core.security.handler;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.GenericFilterBean;
import person.twj.jwt.domain.vo.RsVo;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ErrorHandler  extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if("/error".equals(req.getRequestURI())){
            log.debug("{}","");
            Map<String, Object> map = new HashMap<>();
            req.getAttributeNames().asIterator().forEachRemaining(name->{
                if(name.startsWith("jakarta.servlet.error")){
                    map.put(name, req.getAttribute(name));
                }
            });
            RsVo.failed(500, null,map).writeTo((HttpServletResponse) response);
        }else{
            chain.doFilter(request,response);
        }


    }
}
